package cn.diancan.Tags.freemarker;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.apache.struts2.views.freemarker.ScopesHashModel;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.util.ValueStack;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;


public class MyFreemarkerManager extends FreemarkerManager{

	@Override
	protected Configuration createConfiguration(ServletContext servletContext)throws TemplateException {
		/*Configuration cfg= super.createConfiguration(servletContext);
		//设置字符集  
	    cfg.setDefaultEncoding("UTF-8");  
		cfg.setSharedVariable("ycs_food_type_list", new FoodTypeDirective());  
		return cfg;*/
		Configuration config = super.createConfiguration(servletContext);
		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); 
		 Map<String,TemplateDirectiveModel> beans=ctx.getBeansOfType(TemplateDirectiveModel.class);
		for (String key : beans.keySet()){
			Object bean = beans.get(key);
			if (bean != null && bean instanceof TemplateDirectiveModel)
				config.setSharedVariable(key, bean);
		} 
		config.setTemplateUpdateDelay(0);//6000
		config.setCacheStorage(new freemarker.cache.MruCacheStorage(20, 250));
		DateFormateDirectiveModel df = new DateFormateDirectiveModel();
		config.setSharedVariable("dateFormat", df);
		config.setObjectWrapper(new DefaultObjectWrapper());
		config.setDefaultEncoding("UTF-8");
		config.setLocale(java.util.Locale.CHINA);
		config.setEncoding(java.util.Locale.CHINA, "UTF-8");
		System.out.println("加载freemarker");
		return config;
	}

	@Override
	public ScopesHashModel buildTemplateModel(ValueStack arg0, Object arg1,ServletContext arg2, HttpServletRequest arg3,
			HttpServletResponse arg4, ObjectWrapper arg5) {
		// TODO Auto-generated method stub
		return super.buildTemplateModel(arg0, arg1, arg2, arg3, arg4, arg5);
	}
	
	

}